package com.ruoyi.file.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.minio.MinioClient;
import io.minio.BucketExistsArgs;

/**
 * Minio 配置信息
 *
 * @author ruoyi
 */
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig
{
    private static final Logger log = LoggerFactory.getLogger(MinioConfig.class);
    
    /**
     * 服务地址
     */
    private String url;

    /**
     * 用户名
     */
    private String accessKey;

    /**
     * 密码
     */
    private String secretKey;

    /**
     * 存储桶名称
     */
    private String bucketName;

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    public String getAccessKey()
    {
        return accessKey;
    }

    public void setAccessKey(String accessKey)
    {
        this.accessKey = accessKey;
    }

    public String getSecretKey()
    {
        return secretKey;
    }

    public void setSecretKey(String secretKey)
    {
        this.secretKey = secretKey;
    }

    public String getBucketName()
    {
        return bucketName;
    }

    public void setBucketName(String bucketName)
    {
        this.bucketName = bucketName;
    }

    @Bean
    public MinioClient getMinioClient()
    {
        try {
            MinioClient client = MinioClient.builder()
                .endpoint(url)
                .credentials(accessKey, secretKey)
                .build();
            
            // 测试连接
            testConnection(client);
            
            log.info("MinIO客户端初始化成功，服务地址: {}", url);
            return client;
        } catch (Exception e) {
            log.error("MinIO客户端初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("MinIO客户端初始化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 测试MinIO连接
     */
    private void testConnection(MinioClient client) throws Exception {
        try {
            // 测试存储桶是否存在
            boolean exists = client.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
            
            if (!exists) {
                log.warn("MinIO存储桶 '{}' 不存在，将在首次上传时自动创建", bucketName);
            } else {
                log.info("MinIO存储桶 '{}' 连接正常", bucketName);
            }
        } catch (Exception e) {
            log.error("MinIO连接测试失败: {}", e.getMessage());
            throw e;
        }
    }
}
